/* File:        	ResponseSerializedImpl.java
* Package:			org.esi.authz.common.comm.response
* Created:      	29-abr-2011
* Last Changed: 	0:10:47
* Author:       	Borja Urkizu borja.urquizu@tecnalia.com
*
*   
* History:
*  Revision 1.0.0.0  
* 
* Tecnalia Research and Innovation
*/
package com.tecnalia.authz.common.comm.response;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jboss.security.xacml.factories.RequestResponseContextFactory;
import org.jboss.security.xacml.interfaces.ResponseContext;

import com.tecnalia.authz.common.log.PDPLog;


// TODO: Auto-generated Javadoc
/**
 * The Class ResponseSerializedImpl.
 */
public class ResponseSerializedImpl implements Serializable, IResponseSerialized {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The responselist. */
   	//private PDPLog logger = new PDPLog(ResponseSerializedImpl.class);
		
   	/** The Response List. */
	public List<String> responselist = new ArrayList<String>();
	
	/* (non-Javadoc)
	 * @see org.esi.authz.common.comm.response.IResponseSerialized#serializeResponse(org.jboss.security.xacml.interfaces.ResponseContext[])
	 */
	@Override
	public void serializeResponse(ResponseContext[] responseAuthz) {
		// TODO Auto-generated method stub
		
	
		for (int i = 0; i < responseAuthz.length; i++) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			try {
				responseAuthz[i].marshall(baos);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			 
			this.responselist.add(baos.toString());
	
			if ( PDPLog.logger.isDebugEnabled() ){
				//this.logger.debug("SERVER Response : " + baos.toString()); 
			}
	
		}

	}

	/* (non-Javadoc)
	 * @see org.esi.authz.common.comm.response.IResponseSerialized#deserializeResponse()
	 */
	@Override
	public ResponseContext[] deserializeResponse(){
        
        ResponseContext[] response = new ResponseContext[this.responselist.size()];

		int i = 0;
        for (Iterator<String> iterator = this.responselist.iterator(); iterator.hasNext();) {
        	ResponseContext resC = RequestResponseContextFactory.createResponseContext();

			String resPlain = iterator.next();
			InputStream is;
			try {
				is = new ByteArrayInputStream(resPlain.getBytes("UTF-8"));
				resC.readResponse(is);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
	        response[i] = resC;

	        //
	       i++;
		}
        return response;
	}	

}
